package glassline;

import glassline.interfaces.Robot;
import glassline.interfaces.RobotConveyor;

import java.util.Timer;
import java.util.TimerTask;

public class RobotConveyorAgent extends ConveyorAgent implements RobotConveyor {
	Robot previousComponent;
	
	public RobotConveyorAgent(int id) {
		super(id);
	}

	// Scheduler
	
	@Override
	public boolean pickAndExecuteAnAction() {
		// Rule: Prevents collisions by moving a glass onto a stopped conveyor with glass at the beginning.
		if (on && !nextSpaceAvailable()) {
			if (endSensor.isSensing) {
				stop();
				return true;
			}
		}
		
		// Rule: Restarts conveyor if nothing is blocking the glass.
		if (!on && nextSpaceAvailable()) {
			start();
			return true;
		}
	
		// Rule: Process a sensor state change.
		if (!sensorHits.isEmpty()) {
			ConveyorSensor sensor = sensorHits.get(0);
			sensorHits.remove(0);
		
			if (sensor == endSensor) {
				if (sensor.isSensing) { // Glass just triggered sensor
					
				}
				else { // Glass just left sensor
					passGlassForward();
					return true;
				}
			}
			else if (sensor == beginningSensor) {
				if (sensor.isSensing) { // Glass just triggered sensor
					tellRobotGlassReceived();
					
					if (!on && !sentAlertGlassBlockingEntry) {
						alertPreviousComponent();
					}
					
					return true;
				}
				else { // Glass just left sensor
					
				}
			}
			return true;
		}
		return false;
	}
	
	// Actions
	
	protected void tellRobotGlassReceived() {
		// Wait 500ms because there is a small gap between the glass hitting the first sensor and being fully on the conveyor.
		new Timer().schedule(new TimerTask() { 
			public void run() {
				previousComponent.msgReceivedGlass(); // Tell robot the glass made it to the line.
			}
		}, 4000);
	}
	
	// Setters
	
	public void setPreviousComponent(Robot robot) {
		previousComponent = robot;
	}
}
